package com.kuaimacode.kframework.agent.services.agent;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.andyczy.java.excel.ExcelUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.vo.request.AgentOrderReq;
import com.kuaimacode.kframework.agent.vo.response.AgentIndexTop1;
import com.kuaimacode.kframework.agent.vo.response.AgentOrderResp;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.mapper.agent.SysAgentMapper;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgentOrder;
import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @date 2019/03/31
 */
@Service
public class SysAgentService extends ServiceImpl<SysAgentMapper, SysAgent> {
    /**
     * 分页查找所有的数据
     *
     * @param pageNum  当前页码，从1开始
     * @param pageSize 一页显示多少行
     * @return
     */
    public PageInfo<SysAgent> findAll(int pageNum, int pageSize, SysAgent searchAgent) {
//        List<SysAdminUser> adminUsers = adminUserService.list();
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<SysAgent> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(searchAgent.getName())) {
            wrapper.like("name", searchAgent.getName());
        }
        wrapper.orderByAsc("stat");
        List<SysAgent> datas = baseMapper.selectList(wrapper);
        /*if (adminUsers != null) {
            Optional.ofNullable(datas)
                    .ifPresent(sysAgents -> sysAgents.forEach(sysAgent -> {
                        adminUsers.stream().filter(adminUser -> adminUser.getUserId().equals(sysAgent.getOpenBy()))
                                .findFirst().ifPresent(adminUser -> sysAgent.setOpenName(adminUser.getUserName()));
                    }));
        }*/
        return new PageInfo<>(datas);
    }

    /**
     * 分站是否存在
     * @param agentId
     * @return
     */
    public boolean hasAgent(String agentId) {
        return baseMapper.selectById(agentId) == null;
    }

    /**
     * 关闭分站
     * @param agentId
     * @return
     */
    public boolean closeAgent(String agentId) {
        SysAgent agent = baseMapper.selectById(agentId);
        if (agent == null) {
            throw new ServerInternalErrorException(ErrorEnum.AGENT_NOT_NORMAL_OR_NOT_EXIST);
        }

        SysAgent updateAgent = new SysAgent();
        updateAgent.setId(agentId);
        updateAgent.setStat(1);
        return baseMapper.updateById(updateAgent) == 1;
    }
    /**
     * 根据行政区划代码获取分站信息
     * @param id
     * @return
     */
    public SysAgent getAgentInfoById(String id){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("stat","0");
        wrapper.eq("id",id);
        return baseMapper.selectOne(wrapper);
    }


    /**
     * 更新分站账户余额
     */
    public int updateBal(String agentId, String inOut, BigDecimal amount){
        return baseMapper.updateBalance(agentId,inOut,amount);

    }

    public Map<String, BigDecimal> findCollectInfo(AgentOrderReq orderReq) {
        if (DateUtil.dayDiff(DateUtil.stringtoDate(orderReq.getStartTime(), DateUtil.LONG_DATE_FORMAT), DateUtil.stringtoDate(orderReq.getEndTime(), DateUtil.LONG_DATE_FORMAT)) > 31) {
            throw new ServerInternalErrorException("相隔天数不能超过31天");
        }
        return baseMapper.findCollectInfo(orderReq.getAgentId(), orderReq.getTranType(),
                DateUtil.stringtoDate(orderReq.getStartTime(), DateUtil.LONG_DATE_FORMAT),
                DateUtil.stringtoDate(orderReq.getEndTime(), DateUtil.LONG_DATE_FORMAT));
    }

    /**
     * 分站管理页面查看订单数据详情
     * @param orderReq
     * @param pageInfo
     * @return
     */
    public List<AgentOrderResp> findAgentOrderDetail(AgentOrderReq orderReq, int pageNum, int pageSize) {
        if (orderReq.getTranType() == null) {
            orderReq.setTranType("");
        }
        List<SysAgentOrder> agentOrderList = baseMapper.findAgentOrderDetail(orderReq.getAgentId(), orderReq.getTranType(),
                DateUtil.stringtoDate(orderReq.getStartTime(), DateUtil.LONG_DATE_FORMAT),
                DateUtil.plus(DateUtil.stringtoDate(orderReq.getEndTime(), DateUtil.LONG_DATE_FORMAT), DateUtil.DateEnum.DAY, 1), 0, 50);

        Map<String, AgentOrderResp> orderRespMap = DateUtil.getBetweenDate(orderReq.getStartTime(), orderReq.getEndTime())
                .stream().collect(Collectors.toMap(date -> date, date -> {
                    AgentOrderResp resp = AgentOrderResp.defaultInstance();
                    resp.setTranTime(DateUtil.stringtoDate(date, DateUtil.LONG_DATE_FORMAT));
                    resp.setTranType(orderReq.getTranType());
                    return resp;
                }));
        Optional.ofNullable(agentOrderList)
                .ifPresent(list -> list.forEach(sysAgentOrder -> {
                    AgentOrderResp resp = orderRespMap.get(sysAgentOrder.getTranTime());
                    if (resp == null) {
                        return;
                    }
                    switch (sysAgentOrder.getType()) {
                        case "agent":
                            resp.setAgentIncome(sysAgentOrder.getAgentMoney());
                            break;
                        case "master":
                            resp.setMasterIncome(sysAgentOrder.getAgentMoney());
                            break;
                        case "valid_count":
                            resp.setValidCount(sysAgentOrder.getAgentMoney().longValue());
                            break;
                        case "invalid_count":
                            resp.setInvalidCount(sysAgentOrder.getAgentMoney().longValue());
                            break;
                        case "coupon_amount":
                            resp.setOffer(sysAgentOrder.getAgentMoney());
                            break;
                        default:
                    }
                }));
        List<AgentOrderResp> orderRespList = orderRespMap.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
        Collections.sort(orderRespList, (order1, order2) -> {
            if (order1.getTranTime().getTime() < order2.getTranTime().getTime()) {
                return 1;
            } else if (order1.getTranTime().getTime() > order2.getTranTime().getTime()) {
                return -1;
            } else {
                return 0;
            }
        });
        return orderRespList;
    }

    /**
     * 分站数据导出
     * @param orderReq
     * @param pageNum
     * @param pageSize
     * @param response
     */
    public void agentOrderExport(AgentOrderReq orderReq, int pageNum, int pageSize, HttpServletResponse response) {
        List<AgentOrderResp> list = this.findAgentOrderDetail(orderReq, pageNum, pageSize);

        List<List<String[]>> dataLists = new ArrayList<>();
        List<String[]> oneList = new ArrayList<>();
        String[] headers = {"日期", "业务类型", "平台收益", "分站收益", "师傅收益", "优惠款", "未入账", "有效单数", "取消单数"};
        oneList.add(headers);
        Optional.ofNullable(list)
                .ifPresent(resps -> resps.forEach(resp -> {
                    String[] values = new String[]{DateUtil.format(resp.getTranTime(), DateUtil.LONG_DATE_FORMAT), resp.exchangeTranType(),
                            resp.getPlatformIncome().toString(), resp.getAgentIncome().toString(), resp.getMasterIncome().toString(), resp.getOffer().toString(),
                            resp.getNotAccounted().toString(), resp.getValidCount().toString(), resp.getInvalidCount().toString()};
                    oneList.add(values);
                }));
        dataLists.add(oneList);

        ExcelUtils excelUtils = ExcelUtils.initialization();
        excelUtils.setDataLists(dataLists);
        excelUtils.setSheetName(new String[]{"分站数据"});
        excelUtils.setResponse(response);
        // 执行导出
        excelUtils.exportForExcelsOptimize();
    }

    /**
     * 查询首页信息
     * @param agentId
     * @return
     */
    public Map<String, Object> agentIndex(String agentId) {
        List<Map<String, Object>> mapList = baseMapper.findIndexTop1(agentId);
        AgentIndexTop1 agentIndexTop1 = new AgentIndexTop1();
        mapList.forEach(map -> {
            String type = (String) map.get("type");
            BigDecimal money = (BigDecimal) map.get("money");
            switch (type) {
                case "agent_money":
                    agentIndexTop1.setAgentMoney(money);
                    break;
                case "agent_income":
                    agentIndexTop1.setAgentIncome(money);
                    break;
                case "balance":
                    agentIndexTop1.setBalance(money);
                    break;
                case "master_income":
                    agentIndexTop1.setMasterIncome(money);
                    break;
                case "master_balance":
                    agentIndexTop1.setMasterBalance(money);
                    break;
                default:

            }
        });

        Map<String, String> todayInfo = baseMapper.findIndexTop2Left(new Date(), agentId);
        Map<String, String> yestodyInfo = baseMapper.findIndexTop2Left(DateUtil.plus(DateUtil.DateEnum.DAY, -1), agentId);
        Map<String, String> right = baseMapper.findIndexTop2Right(agentId);

        Map<String, Object> map = new HashMap<>();
        map.put("agentIndexTop1", agentIndexTop1);
        map.put("todayInfo", todayInfo);
        map.put("yestodyInfo", yestodyInfo);
        map.put("right", right);
        return map;
    }
}

